import React from 'react';
import { connect } from 'umi';
import { Layout, Modal } from 'antd';
import config from "../config/config";
import HeadMainMenu from '../components/module/HeadMainMenu';
import SideSubMenu from '../components/module/SideSubMenu';
import ModuleContent from '../components/module/ModuleContent';
import ThemeDrawer from '../components/theme/ThemeDrawer';
import styles from "./index.css";
import 'remixicon/fonts/remixicon.css';
import * as moduleService from '../services/moduleService';

const { Header, Content, Sider } = Layout;

/**
 * 顶部主菜单及其内容
 */
const ModulePage = (props) => {

  const { dispatch, history, moduleModel, messageModel, userInfoModel } = props;
  let {
    collapsed, activeHeadMenuKey, activeSideMenuKey, menuData, paneTabs, themeStyle, siderColor,
    openedSubMenuKey, homeView, tokenModel, themeDrawerVisible, themeColor, selectedStyle,
    userInfoVisible, systemStatus
  } = moduleModel;
  const { userInfoData, roleInfoData } = userInfoModel;
  const { noficationList, messageList, todoList, badgeCount } = messageModel;
  console.log("ApplicationPage activeHeadMenuKey activeSideMenuKey => ", activeHeadMenuKey, activeSideMenuKey);
  console.log("ApplicationPage paneTabs => ", paneTabs);

  const headMainMenuProps = {
    collapsed,
    activeHeadMenuKey,
    activeSideMenuKey,
    menuData,
    tokenModel,
    themeStyle,
    themeColor,
    noficationList,
    messageList,
    todoList,
    badgeCount,
    systemStatus,
    toggleSiderMenu: () => {
      dispatch({ type: "moduleModel/updateState", payload: { collapsed: !collapsed }});
    },
    onSelectHeadMenu: (params) => {
      const { item, key, keyPath } = params;
      const sideMenu = menuData.sider[key];
      let openedSubMenuKey, activeSideMenuKey;
      if (sideMenu) {
        const isExist = paneTabs.filter(item => item.key == sideMenu[0].key).length > 0 ? true : false;
        const isHasChild = sideMenu[0].children ? true : false;
        if (!isExist && !isHasChild) {
          let sideMenuList = sideMenu.filter(item => item.show);
          activeSideMenuKey = sideMenuList[0].key;
          paneTabs.push({...sideMenuList[0]});
        } else if (isHasChild) {
          openedSubMenuKey = sideMenu[0].key;
          activeSideMenuKey = sideMenu[0].children[0].key;
          const isExistChild = paneTabs.filter(item => activeSideMenuKey == item.key).length > 0 ? true : false;
          if (!isExistChild) {
            paneTabs.push({...sideMenu[0].children[0], key: activeSideMenuKey});
          }
        }
      }
      activeSideMenuKey = activeSideMenuKey ? activeSideMenuKey : sideMenu ? sideMenu[0].key : "home";
      openedSubMenuKey = openedSubMenuKey ? openedSubMenuKey : "home";
      dispatch({ type: "moduleModel/updateState", payload: { activeHeadMenuKey: key, paneTabs, activeSideMenuKey, openedSubMenuKey, userInfoVisible: false }});
    },
    onSelectSideMenu: (params) => {
      const { item, key } = params;
      const pathUrl = menuData.list.filter(item => key == item.key);
      const isExist = paneTabs.filter(item => item.key == pathUrl[0].key).length > 0 ? true : false;
      if (!isExist) {
        paneTabs.push({...pathUrl[0]});
      }
      dispatch({ type: "moduleModel/updateState", payload: { activeSideMenuKey: key, paneTabs, pageUrl: item.props.path }});
    },
    onShowUserInfo: () => {
      dispatch({ type: "moduleModel/updateState", payload: { activeHeadMenuKey: "userInfo", activeSideMenuKey: "userInfo", userInfoVisible: true }});
    },
    onLogout: () => {
      Modal.confirm({
        title: '提示',
        okText: "确认",
        cancelText: "取消",
        content: <div><i className="ri-error-warning-line" style={{fontSize: "18px", marginRight: "10px", verticalAlign: "sub"}}></i>确定要退出系统？</div>,
        onOk() {
          Promise.all([dispatch({ type: "moduleModel/logout", payload: {}})]).then(() =>
            window.location.href = "http://localhost:8000"
          );
        },
        onCancel() {},
      });
    },
    onSystemInfo: () => {
      dispatch({ type: "moduleModel/addActiveRoute", payload: { key: "info" }});
    },
    onTheme: () => {
      dispatch({ type: "moduleModel/updateState", payload: { themeDrawerVisible: true }});
    },
    clearPane: (paneKey) => {
      dispatch({ type: "messageModel/clearPane", payload: { paneKey }});
    },
    onDetail: (key) => {
      dispatch({ type: "messageModel/onDetail", payload: { key }});
    },
    onShowAppSelect: () => {
      sessionStorage.systemStatus = "app";
      dispatch({ type: "moduleModel/updateState", payload: { systemStatus: "app" }});
      window.location.href = "http://localhost:8000/app";
    },
  }

  const sideTabMenuProps = {
    history,
    collapsed,
    activeHeadMenuKey,
    activeSideMenuKey,
    menuData,
    paneTabs,
    openedSubMenuKey,
    homeView,
    tokenModel,
    themeStyle,
    siderColor,
    themeColor,
    roleInfoData,
    userInfoVisible,
    systemStatus,
    userInfoData,
    onSelectSideMenu: (params) => {
      const { item, key } = params;
      const pathUrl = menuData.list.filter(item => key == item.key);
      const isExist = paneTabs.filter(item => item.key == pathUrl[0].key).length > 0 ? true : false;
      if (!isExist) {
        paneTabs.push({...pathUrl[0]});
      }
      dispatch({ type: "moduleModel/updateState", payload: { activeSideMenuKey: key, paneTabs, pageUrl: item.props.path }});
    },
    onOpenSubMenu: (openedKey) => {
      dispatch({ type: "moduleModel/updateState", payload: { openedSubMenuKey: openedKey }});
    },
    onSaveUserInfo: () => {
      dispatch({ type: "moduleModel/updateState", payload: { activeHeadMenuKey: "home" }});
    },
    onCloseUserInfo: () => {
      dispatch({ type: "moduleModel/updateState", payload: { activeHeadMenuKey: "home", activeSideMenuKey: "home", userInfoVisible: false }});
    },
    cacheUserData: (userInfoData) => {
      dispatch({ type: "userInfoModel/updateState", payload: { userInfoData }});
    }
  }

  const contentTabFrameProps = {
    history,
    collapsed,
    activeHeadMenuKey,
    activeSideMenuKey,
    menuData,
    paneTabs,
    openedSubMenuKey,
    homeView,
    tokenModel,
    themeStyle,
    siderColor,
    themeColor,
    roleInfoData,
    userInfoVisible,
    systemStatus,
    userInfoData,
    onTabChange: (activeTabKey) => {
      let activeHeadKey = moduleService.buildMenuMap(menuData.list, activeTabKey);
      dispatch({ type: "moduleModel/updateState", payload: { activeSideMenuKey: activeTabKey, activeHeadMenuKey: activeHeadKey }});
    },
    removeTab: (targetKey, activeTabKey) => {
      let panes = paneTabs.filter(item => item.key != targetKey);
      const activedPane = panes.filter(item => activeTabKey == item.key);
      const activeKey = activedPane.length > 0 ? activeTabKey : panes.length == 0 ? null : panes[panes.length - 1].key;
      let activeHomeKey = menuData.main[0].key;
      if (activeKey) {
        const activeSubMenu = menuData.list.filter(item => item.key == activeKey)[0];
        const activeMenu = menuData.list.filter(item => item.id == activeSubMenu.parentId)[0];
        activeHomeKey = activeMenu.key;
      }
      if (panes.length == 0) {
        activeHomeKey = menuData.main[0].key;
      }
      dispatch({ type: "moduleModel/updateState",
        payload: {
          paneTabs: panes,
          activeSideMenuKey: activeKey,
          activeHeadMenuKey: activeHomeKey
        }});
    },
    closeCurrentTab: () => {
      if ("platform" == activeSideMenuKey) {
        return;
      }
      let closeTabs = paneTabs.filter(item => item.key != activeSideMenuKey);
      const activeTabKey = closeTabs.length > 0 ? closeTabs[closeTabs.length - 1].key : null;
      let activeKey = activeHeadMenuKey;
      if (closeTabs.length == 0) {
        activeKey = menuData.main[0].key;
      }
      dispatch({ type: "moduleModel/updateState", payload: { paneTabs: closeTabs, activeSideMenuKey: activeTabKey, activeHeadMenuKey: activeKey }});
    },
    closeOtherTab: () => {
      let closeTabs = paneTabs.filter(item => item.key == activeSideMenuKey || "platform" == item.key);
      let activeKey = activeHeadMenuKey;
      if (closeTabs.length == 0) {
        activeKey = menuData.main[0].key;
      }
      dispatch({ type: "moduleModel/updateState", payload: { paneTabs: closeTabs, activeHeadMenuKey: activeKey }});
    },
    onCloseTab: () => {
      let closeTabs = paneTabs.filter(item => "platform" == item.key);
      dispatch({ type: "moduleModel/updateState", payload: { paneTabs: closeTabs, activeHeadMenuKey: menuData.main[0].key, activeSideMenuKey: "platform" }});
    },
  }

  const themeDrawerProps = {
    themeDrawerVisible,
    themeColor,
    siderColor,
    themeStyle,
    selectedStyle,
    onClose: () => {
      dispatch({ type: "moduleModel/updateState", payload: { themeDrawerVisible: false }});
    },
    onChangeColor: (type, color) => {
      const payload = type == "preset" ? {themeColor: color} : selectedStyle == "theme" ? { themeColor: color } : { siderColor: color };
      dispatch({ type: "moduleModel/updateState", payload });
    },
    onDefaultColor: () => {
      dispatch({ type: "moduleModel/updateState", payload: { themeColor: config.DEFAULT_THEME_COLOR, siderColor: config.DEFAULT_SIDER_COLOR }});
    },
    onSelectStyle: (e) => {
      dispatch({ type: "moduleModel/updateState", payload: { selectedStyle: e.target.value }});
    },
  }

  const width = window.innerWidth;
  const height = window.innerHeight;
  return (
    <Layout style={{ width, height, background: "#fff", display: "block" }}>
      {/* 菜单导航 */}
      <Header style={{ height: "55px", background: themeColor }}>
        <HeadMainMenu {...headMainMenuProps} />
      </Header>

      <Content className={collapsed ? styles.content_main_layout_collapse : styles.content_main_layout}>
        {/* 左侧子菜单 */}
        <Sider collapsible collapsed={collapsed} className={styles.side_sub_menu}>
          <SideSubMenu {...sideTabMenuProps} />
        </Sider>

        {/* 页面Tab内容 */}
        <ModuleContent {...contentTabFrameProps} />
      </Content>

      {/* 主题设置 */}
      <ThemeDrawer {...themeDrawerProps} />
    </Layout>
  )
}

function mapStateToProps({ moduleModel, messageModel, userInfoModel }) {
  return { moduleModel, messageModel, userInfoModel };
}

export default connect(mapStateToProps)(ModulePage);
